package com.wuyanzu.shixicoderedo.common.threadpool;

import com.wuyanzu.shixicoderedo.common.threadlocal.RequestContext;
import com.wuyanzu.shixicoderedo.common.threadlocal.RequestContextHolder;
import org.slf4j.MDC;

import java.util.Objects;
import java.util.concurrent.Callable;

/**
 * 业务 Callable 的包装类
 * 核心功能：在执行任务时设置 ThreadLocal + MDC，保证上下文传递
 */
public class ContextAwareCallable<V> implements Callable<V> {

    // 被包装的原始业务 Callable
    private final Callable<V> delegate;

    // 请求上下文，包含 correlationId / patientId
    private final RequestContext ctx;

    // 构造函数，要求 delegate 非空
    public ContextAwareCallable(Callable<V> delegate, RequestContext ctx) {
        this.delegate = Objects.requireNonNull(delegate);
        this.ctx = ctx;
    }

    // 执行方法
    @Override
    public V call() throws Exception {
        try {
            // 将上下文放入当前线程 ThreadLocal
            RequestContextHolder.set(ctx);

            // 将 correlationId / patientId 写入 MDC（日志链路）
            if (ctx != null) {
                if (ctx.getCorrelationId() != null) MDC.put("correlationId", ctx.getCorrelationId());
                if (ctx.getPatientId() != null) MDC.put("patientId", ctx.getPatientId());
            }

            // 执行业务逻辑
            return delegate.call();

        } finally {
            // 清理 MDC 避免线程复用污染
            MDC.remove("correlationId");
            MDC.remove("patientId");

            // 清理 ThreadLocal 避免脏数据
            RequestContextHolder.clear();
        }
    }
}
